package servlet;

import java.io.IOException;
import java.sql.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Category;
import model.Trade;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import persistence.CategoryDao;
import persistence.CustomerDao;
import persistence.TradeDao;

/**
 * Servlet implementation class CreatePost
 */
@WebServlet("/CreatePost")
public class CreatePost extends MyHttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	//TODO Connect the Database
	private void process(HttpServletRequest request,
			HttpServletResponse response) {
		Document xmlDoc = getDocument(request);
		NodeList posContent = xmlDoc.getElementsByTagName("content").item(0).getChildNodes();
		String username = posContent.item(0).getFirstChild().getNodeValue();
		String title = posContent.item(1).getFirstChild().getNodeValue();
		String body = posContent.item(2).getFirstChild().getNodeValue();
		String category_name = posContent.item(3).getFirstChild().getNodeValue();
		String date = posContent.item(4).getFirstChild().getNodeValue();
		String reward = posContent.item(5).getFirstChild().getNodeValue();
		
		Category category = CategoryDao.load(category_name);
		
		Trade trade = new Trade();
		trade.setTitle(title);
		trade.setState(body);
		trade.setCategory(category);
		trade.setDate(Date.valueOf(date));
		trade.setHighPrice(Integer.parseInt(reward));
		trade.setMode(0);
		TradeDao.save(CustomerDao.nameToID(username), trade);
	}

}
